<template>
  <el-dialog :visible.sync="visible" :append-to-body="true"
             :close-on-click-modal="false" :before-close="handleClose"
             title="客户查重" class="no-padding-dialog" width="800px">
    <div v-loading="loading" :class="{ 'show-table': showTable }" class="duplicate-check">
      <div>
        <el-input v-model="searchContent" class="search-input" @keyup.enter="getList">
          <el-select #prepend v-model="typeSelect">
            <el-option label="按客户名称" value="name"/>
            <el-option label="按手机号/电话" value="phone"/>
          </el-select>
          <el-button v-slot:append type="primary" icon="wk wk-search" @click="getList">查重</el-button>
        </el-input>
      </div>

      <el-table v-if="showTable" :data="tableData" :cell-class-name="cellClassName"
                class="duplicate-check__content"
                border
                height="380"
                style="width: 100%"
                @row-click="handleRowClick">
        <el-table-column
            v-for="(item, index) in fieldList"
            :key="index"
            :prop="item.prop"
            :label="item.label"
            :min-width="item.width"
            show-overflow-tooltip/>
        <el-table-column fixed="right" width="110px" label="操作">
          <template v-if="scope.row.poolAuthList" #default="scope">
            <el-button v-if="scope.row.poolAuthList.receive" link size="small"
                       @click="handleClick('receive', scope.row)">领取
            </el-button>
            <el-button v-if="scope.row.poolAuthList.distribute" link size="small"
                       @click="handleClick('distribute', scope.row)">分配
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="showTable" class="duplicate-check__footer">注：查重结果最多显示10条，如不完整，请完善查重条件</div>

      <CRMFullScreenDetail
          :visible.sync="showFullDetail"
          :crm-type="relationCrmType"
          :id="relationId"
          :pool-id="poolId"
          @handle="getList"/>

      <AllocHandle
          :pool-id="poolId"
          :selection-list="[relationData]"
          v-model:dialog-visible="allocDialogShow"
          crm-type="customer"
          @handle="getList"/>
    </div>
  </el-dialog>
</template>

<script setup>
import AllocHandle from '../SelectionHandle/AllocHandle.vue' // 公海分配操作
import CRMFullScreenDetail from "components/CRMFullScreenDetail.vue";

import {crmCustomerDataCheckAPI, crmCustomerReceiveAPI} from "@/api/crm/customer.js";
import crmTypeModel from "@/views/crm/model/crmTypeModel.js";
import {computed, watch, ref} from "vue"

defineOptions({
  name: 'DuplicateCheckSingle',
})

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const loading = ref(false)
const typeSelect = ref('name')
const searchContent = ref('')
const tableData = ref(null)

const showFullDetail = ref(false) // 查看相关客户管理详情
const relationId = ref('') // 相关ID参数
const relationData = ref({}) // 关联数据
const poolId = ref('') // 公海Id
const relationCrmType = ref('') // 相关类型
const allocDialogShow = ref(false) //  分配弹窗

const showTable = computed(() => {
  return tableData.value
})

const isCustomerFilter = computed(() => {
  return typeSelect.value == 'name'
})

// 客户名称、创建时间、负责人、最后跟进时间、操作
const fieldList = computed(() => {
  if (isCustomerFilter.value) {
    return [{
      prop: 'name',
      label: '客户名称',
      width: 200
    }, {
      prop: 'createTime',
      label: '创建时间',
      width: 160
    }, {
      prop: 'ownerUserName',
      label: '负责人',
      width: 100
    }, {
      prop: 'lastTime',
      label: '最后跟进时间',
      width: 160
    }, {
      prop: 'module',
      label: '模块',
      width: 100
    }]
  }

  return [{
    prop: 'mobile',
    label: '手机号/电话',
    width: 160
  }, {
    prop: 'contactsName',
    label: '联系人',
    width: 160
  }, {
    prop: 'name',
    label: '客户名称',
    width: 200
  }, {
    prop: 'ownerUserName',
    label: '负责人',
    width: 100
  }, {
    prop: 'module',
    label: '模块',
    width: 100
  }]
})

watch(typeSelect, () => {
  searchContent.value = ''
  tableData.value = null
})


function handleClose() {
  emits('update:visible', false)
  resetData()
}

function resetData() {
  typeSelect.value = 'name'
  searchContent.value = ''
  tableData.value = null
}

function getList() {
  if (!searchContent.value) {
    return
  }
  const params = {}
  params[typeSelect.value] = searchContent.value
  loading.value = true
  crmCustomerDataCheckAPI(params).then(res => {
    loading.value = false
    const list = res.data || []
    tableData.value = list.map(item => {
      item.module = crmTypeModel.convertTypeToName(item.type)
      if (item.poolName) {
        item.module = `${item.module}（${item.poolName}）`
      }
      // 是手机号
      if (!isCustomerFilter.value) {
        item.mobile = searchContent.value
        if (item.type == crmTypeModel.contacts) {
          item.contactsName = item.name
          item.contactsId = item.id

          item.name = item.customerName
          item.id = item.customerId
          // name 字段对应的点击类型 以type为准，所以将type校准为客户
          // 联系人详情 已 contactsId 为准
          item.type = crmTypeModel.customer
        }
      }
      return item
    })
  }).catch(() => {
    loading.value = false
  })
}

/**
 * 列表点击
 */
function handleRowClick(row, column, event) {
  if (column.property == 'name' && row.id) {
    relationId.value = row.id
    if (row.poolAuthList) {
      poolId.value = row.poolAuthList.poolId
    } else {
      poolId.value = ''
    }
    const key = crmTypeModel.convertTypeToKey(row.type)
    relationCrmType.value = key == 'pool' ? 'customer' : key
    showFullDetail.value = true
  } else if (column.property == 'contactsName' && row.contactsId) {
    relationId.value = row.contactsId
    relationCrmType.value = 'contacts'
    showFullDetail.value = true
  }
}

/**
 * 通过回调控制class
 */
function cellClassName({row, column, rowIndex, columnIndex}) {
  if (column.property === 'name' || column.property === 'contactsName') {
    return 'can-visit--underline'
  } else {
    return ''
  }
}

function handleClick(type, data) {
  if (type === 'receive') {
    ElMessageBox.confirm('确定要领取该客户吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
        .then(() => {
          crmCustomerReceiveAPI({
            ids: [data.id],
            poolId: data.poolAuthList.poolId
          })
              .then(res => {
                ElMessage.success({message: '操作成功'})
                getList()
              })
              .catch(() => {
              })
        })
        .catch(() => {
        })
  } else {
    data['customerId'] = data.id
    relationData.value = data
    allocDialogShow.value = true
  }
}
</script>

<style scoped lang="scss">
.duplicate-check {
  position: relative;
  padding: 20px;
  padding-bottom: 40px;

  &__content {
    margin-top: 15px;
  }

  &__footer {
    margin-top: 10px;
    font-size: 12px;
    color: #666;
  }
}

.duplicate-check.show-table {
  padding-bottom: 20px;
}

.el-input {
  :deep(.el-select .el-input) {
    width: 130px;

    :deep(i) {
      font-weight: bold;
    }
  }

  :deep(.el-input-group__append ) {
    background-color: $xr-color-primary;
    border-color: $xr-color-primary;
    color: white;

    .el-button {
      :deep(i ) {
        margin-right: 5px;
        font-size: 14px;
      }
    }
  }
}
</style>
